package demo.socket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.ByteBuffer;


public class ServerSock {
	public static void main(String[] args) {
		ServerSocket serverSocket = null;
		try {
			serverSocket = new ServerSocket(1234);
			System.out.println("Tao server thanh cong");
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		Socket clientSocket = null;
		try {
			clientSocket = serverSocket.accept();
			InputStream is = clientSocket.getInputStream();
			byte[] arrLeg = new byte[4];
			is.read(arrLeg);
			int leg = ByteBuffer.wrap(arrLeg).getInt();
			
			byte[] bt = new byte[leg];
			is.read(bt);
			String data;
			data = new String(bt);
			System.out.println(data);
			data += "_Qua server";

			OutputStream os = clientSocket.getOutputStream();
			leg = data.length();
			arrLeg = ByteBuffer.allocate(4).putInt(leg).array();
			os.write(arrLeg);
			os.write(data.getBytes());
			is.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		try {
			if(clientSocket != null)
				clientSocket.close();
			if(serverSocket != null)
				serverSocket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
